﻿using Aspose.Cells;
using Aspose.Cells.Rendering;
using ProjectCloth.Entity;
using ProjectCloth.Entity.Enum;
using ProjectCloth.FrmUI.Common;
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Windows.Forms;

namespace ProjectCloth.FrmUI
{
    public partial class DraftOrderFrm : UserControl
    {
        private ClothContext db = new ClothContext();
        private List<Entity.Product> productList = new List<Entity.Product>();
        private int _size = 1;
        public DraftOrderFrm()
        {
            InitializeComponent();
            productList = db.Products.ToList();
            Initial();
            _size = 1;
        }
        public DraftOrderFrm(string orderNo)
        {

            InitializeComponent();
            this.printShowBtn.Text = "预览";
            saveOrderBtn.Enabled = false;
            productList = db.Products.ToList();
            _size = 1;
            makerCbx.DataSource = db.Users.Where(o => o.Enabled == true).ToList();
            makerCbx.DisplayMember = "Name";
            makerCbx.ValueMember = "Id";
            DataGridViewComboBoxColumn GenderColumn = Unit as DataGridViewComboBoxColumn;
            GenderColumn.Items.Add("米");
            GenderColumn.Items.Add("码");
            var draftOrder = db.DraftOrders.Where(o => o.OrderNo == orderNo).FirstOrDefault();
            if (draftOrder != null)
            {
                var draftOrderItems = db.DraftOrderItems.Where(o => o.DraftOrderId == draftOrder.Id).ToList();
                if (draftOrderItems != null && draftOrderItems.Count > 0)
                {
                    orderNoTxt.Text = draftOrder.OrderNo;
                    //customerTxt.Text= draftOrder.cum;
                    makerCbx.SelectedValue = draftOrder.MakerId;
                    summaryTxt.Text = draftOrder.Summary;
                    RemarkTxt.Text = draftOrder.Remark;
                    CompanyNameTxt.Text = draftOrder.CompanyName;
                    LiaisonTxt.Text = draftOrder.Liaison;
                    PhoneTxt.Text = draftOrder.Phone;
                    AmountTxt.Text = draftOrder.TotalAmount.ToString();
                    dataGridView1.Refresh();
                    dataGridView1.AutoGenerateColumns = false;
                    //dataGridView1.Columns["ProductNo"].Visible = false;
                    //dataGridView1.Columns["ProductCode"].Visible = true;
                    //dataGridView1.Columns["ProductCode"].DisplayIndex = 0;
                    //dataGridView1.Columns["OrderItemStatus"].Visible = true;
                    //dataGridView1.Columns["OrderItemId"].Visible = false;
                    var itemsSource = from o in draftOrderItems.ToList()
                                      select new
                                      {
                                          o.ProductNo,
                                          o.ColorType,
                                          Unit = EnumDefine.GetEnumDescription((Unit)o.Unit),
                                          o.VatNo,
                                          o.Roll_1,
                                          o.Roll_2,
                                          o.Roll_3,
                                          o.Roll_4,
                                          o.Roll_5,
                                          o.Roll_6,
                                          o.Roll_7,
                                          o.Roll_8,
                                          o.Roll_9,
                                          o.Roll_10,
                                          o.Roll_Num,
                                          o.Price,
                                          o.Quantity,
                                          o.Amount,
                                          o.Remark,
                                      };
                    dataGridView1.DataSource = itemsSource.ToList();
                }
            }
        }

        private void Initial()
        {
            makerCbx.DataSource = db.Users.Where(o => o.Enabled == true).ToList();
            makerCbx.DisplayMember = "Name";
            makerCbx.ValueMember = "Id";
            DataGridViewComboBoxColumn GenderColumn = Unit as DataGridViewComboBoxColumn;
            GenderColumn.Items.Add("米");
            GenderColumn.Items.Add("码");
            GenderColumn.DefaultCellStyle.NullValue = "码";
            var prefix = "C";
            var today = DateTime.Now.Date;
            var count = db.DraftOrders.Where(o => o.CreateTime >= today).Count() + 1;
            //var count = db.DraftOrders.Count() + 1;
            var countNo = count.ToString().PadLeft(3, '0');
            var preNo = prefix + "-" + DateTime.Now.Date.ToString("yyyyMMdd") + "-" + countNo;
            while (true)
            {
                if (db.DraftOrders.Where(o => o.OrderNo == preNo).Count() > 0)
                {
                    count++;
                    countNo = count.ToString().PadLeft(3, '0');
                    preNo = prefix + DateTime.Now.Date.ToString("yyyyMMdd") + countNo;
                }
                else
                {
                    break;
                }
            }
            var date = createTimePick.Value;
            orderNoTxt.Text = preNo;
        }
        private string GetNewOrderNo()
        {
            var prefix = "C";
            var today = DateTime.Now.Date;
            var count = db.DraftOrders.Where(o => o.CreateTime >= today).Count() + 1;
            //var count = db.DraftOrders.Count() + 1;
            var countNo = count.ToString().PadLeft(3, '0');
            var preNo = prefix + "-" + DateTime.Now.Date.ToString("yyyyMMdd") + "-" + countNo;
            while (true)
            {
                if (db.DraftOrders.Where(o => o.OrderNo == preNo).Count() > 0)
                {
                    count++;
                    countNo = count.ToString().PadLeft(3, '0');
                    preNo = prefix + DateTime.Now.Date.ToString("yyyyMMdd") + countNo;
                }
                else
                {
                    break;
                }
            }
            return preNo;
        }
        //改变键盘键enter效果
        #region
        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {

            base.ProcessCmdKey(ref msg, keyData);
            var dgv = dataGridView1;
            bool _disable = false;

            switch (keyData)
            {
                case Keys.Enter:
                    if (dgv.CurrentRow != null)
                    {
                        if (dgv.CurrentRow.Cells["ProductNo"] != null && dgv.CurrentRow.Cells["ProductNo"].Value != null)
                        {

                            var productno = dgv.CurrentRow.Cells["ProductNo"].Value.ToString();
                            var product = productList.Where(p => p.ProductNo.Contains(productno)).FirstOrDefault();// productlist.Where(p => p.ProductId == productno).FirstOrDefault();
                            //if (product != null)//&& sel)
                            //{
                            //    dgv.CurrentRow.Cells["Price"].Value = product.BatchPrice;
                            //}
                            if (product != null && dgv.CurrentRow.Cells["Price"].Value == null)
                            {
                                //SendKeys.Send("{Tab}");
                                //dgv.CurrentRow.Cells["ProductNo"].Value = product.ProductNo;
                                //dgv.CurrentRow.Cells["ProductName"].Value = product.Name;
                                //dgv.CurrentRow.Cells["ColorType"].Value = product.ColorType;
                                dgv.CurrentRow.Cells["Price"].Value = _size == 0 ? product.Price : product.BatchPrice;
                                //Unit.DefaultCellStyle.NullValue = _size == 0 ? "米" : "码";

                            }
                            //dgv.CurrentRow.Cells["Sum"].Value =
                            //         Convert.ToDecimal(dgv.CurrentRow.Cells["Price"].Value) * Convert.ToDecimal(dgv.CurrentRow.Cells["Quantity"].Value);//计算金额
                            if (dgv.CurrentRow.Cells["Price"].Selected == true)
                            {
                                dgv.CurrentCell = dgv.CurrentRow.Cells["Remark"];
                                var Roll_1 = Helper.GetIntFromCell(dgv.CurrentRow.Cells["Roll_1"]);
                                var Roll_2 = Helper.GetIntFromCell(dgv.CurrentRow.Cells["Roll_2"]);
                                var Roll_3 = Helper.GetIntFromCell(dgv.CurrentRow.Cells["Roll_3"]);
                                var Roll_4 = Helper.GetIntFromCell(dgv.CurrentRow.Cells["Roll_4"]);
                                var Roll_5 = Helper.GetIntFromCell(dgv.CurrentRow.Cells["Roll_5"]);
                                var Roll_6 = Helper.GetIntFromCell(dgv.CurrentRow.Cells["Roll_6"]);
                                var Roll_7 = Helper.GetIntFromCell(dgv.CurrentRow.Cells["Roll_7"]);
                                var Roll_8 = Helper.GetIntFromCell(dgv.CurrentRow.Cells["Roll_8"]);
                                var Roll_9 = Helper.GetIntFromCell(dgv.CurrentRow.Cells["Roll_9"]);
                                var Roll_10 = Helper.GetIntFromCell(dgv.CurrentRow.Cells["Roll_10"]);
                                var intList = new int[]
                                {
                                    Roll_1,
                                    Roll_2,
                                    Roll_3,
                                    Roll_4,
                                    Roll_5,
                                    Roll_6,
                                    Roll_7,
                                    Roll_8,
                                    Roll_9,
                                    Roll_10
                                };
                                dgv.CurrentRow.Cells["Quantity"].Value = intList.Sum();
                                dgv.CurrentRow.Cells["Roll_Num"].Value = GetIntBiggerZero(intList);
                                var price = Convert.ToDecimal("0" + dgv.CurrentRow.Cells["Price"].Value.ToString());
                                dgv.CurrentRow.Cells["Amount"].Value = intList.Sum() * price;
                                decimal rowSum = 0;
                                foreach (DataGridViewRow p in dgv.Rows)
                                {
                                    if (Helper.GetDecimalFromCell(p.Cells["Amount"]) > 0)
                                    {
                                        rowSum += Helper.GetDecimalFromCell(p.Cells["Amount"]);
                                    }
                                }
                                AmountTxt.Text = rowSum.ToString();
                            }
                            else SendKeys.Send("{Tab}");

                        }

                    }
                    else
                    {
                        if (LiaisonTxt.Focused == true)
                        {
                            dgv.Focus();
                        }
                        SendKeys.Send("{Tab}");

                    }

                    _disable = true;
                    break;
                //case Keys.F10:
                //    {
                //        ClearBtn_Click(null, null);
                //        _disable = true;
                //        break;
                //    }
                case Keys.F12:
                    {
                        saveOrderBtn_Click(null, null);
                        _disable = true;
                        break;
                    }
                default:
                    break;
            }

            return _disable;
        }
        #endregion
        private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

        }
        private int SaveDraftOrder()
        {
            var draftOrder = db.DraftOrders.Where(o => o.OrderNo == orderNoTxt.Text).FirstOrDefault();
            var isExist = false;
            if (draftOrder == null)
            {
                draftOrder = new DraftOrder()
                {
                    CreateTime = createTimePick.Value,
                    OrderNo = orderNoTxt.Text,
                    CompanyName = CompanyNameTxt.Text,
                    Liaison = LiaisonTxt.Text,
                    OrderStatus = 0,
                    Phone = PhoneTxt.Text,
                    Summary = summaryTxt.Text,
                    CreatorId = LoginInfo.GetLoginInfo().UserId,
                    CreatorName = LoginInfo.GetLoginInfo().UserName,
                    MakerId = Convert.ToInt32(makerCbx.SelectedValue),
                    MakerName = makerCbx.Text,
                };
                db.DraftOrders.Add(draftOrder);
            }
            else
            {
                isExist = true;
                draftOrder.CompanyName = CompanyNameTxt.Text;
                draftOrder.Liaison = LiaisonTxt.Text;
                draftOrder.Phone = PhoneTxt.Text;
                draftOrder.Summary = summaryTxt.Text;
            }
            var result = db.SaveChanges();
            if (result > 0 || isExist)
            {
                //保存体信息
                //TODO
                var draftOrderItemList = db.DraftOrderItems.Where(o => o.DraftOrderId == draftOrder.Id).ToList(); new List<DraftOrderItem>();
                db.DraftOrderItems.RemoveRange(draftOrderItemList);
                db.SaveChanges();
                draftOrderItemList = new List<DraftOrderItem>();
                foreach (DataGridViewRow p in dataGridView1.Rows)
                {
                    if (Helper.GetStringFromCell(p.Cells["ProductNo"]).Length > 0)
                    {
                        var draftOrderItem = new DraftOrderItem
                        {
                            DraftOrderId = draftOrder.Id,
                            ProductNo = Helper.GetStringFromCell(p.Cells["ProductNo"]),
                            ColorType = Helper.GetStringFromCell(p.Cells["ColorType"]),
                            Unit = (int)(Enum.Parse(typeof(Entity.Enum.Unit), p.Cells["Unit"].EditedFormattedValue != null ? p.Cells["Unit"].EditedFormattedValue.ToString().Trim() : (_size == 0 ? "米" : "码"))),//单位 Helper.GetStringFromCell(p.Cells["Unit"]),
                            VatNo = Helper.GetStringFromCell(p.Cells["VatNo"]),
                            Roll_1 = Helper.GetIntFromCell(p.Cells["Roll_1"]),
                            Roll_2 = Helper.GetIntFromCell(p.Cells["Roll_2"]),
                            Roll_3 = Helper.GetIntFromCell(p.Cells["Roll_3"]),
                            Roll_4 = Helper.GetIntFromCell(p.Cells["Roll_4"]),
                            Roll_5 = Helper.GetIntFromCell(p.Cells["Roll_5"]),
                            Roll_6 = Helper.GetIntFromCell(p.Cells["Roll_6"]),
                            Roll_7 = Helper.GetIntFromCell(p.Cells["Roll_7"]),
                            Roll_8 = Helper.GetIntFromCell(p.Cells["Roll_8"]),
                            Roll_9 = Helper.GetIntFromCell(p.Cells["Roll_9"]),
                            Roll_10 = Helper.GetIntFromCell(p.Cells["Roll_10"]),
                            Price = Helper.GetDecimalFromCell(p.Cells["Price"]),
                            CreateTime = DateTime.Now,
                            Remark = Helper.GetStringFromCell(p.Cells["Remark"]),
                        };
                        var rollList = new int[]
                        {
                            draftOrderItem.Roll_1,
                            draftOrderItem.Roll_2,
                            draftOrderItem.Roll_3,
                            draftOrderItem.Roll_4,
                            draftOrderItem.Roll_5,
                            draftOrderItem.Roll_6,
                            draftOrderItem.Roll_7,
                            draftOrderItem.Roll_8,
                            draftOrderItem.Roll_9,
                            draftOrderItem.Roll_10
                        };
                        draftOrderItem.Roll_Num = GetIntBiggerZero(rollList);
                        draftOrderItem.Quantity = rollList.Sum();
                        draftOrderItem.Amount = draftOrderItem.Quantity * draftOrderItem.Price;
                        draftOrderItemList.Add(draftOrderItem);
                    }

                }
                if (draftOrderItemList.Count > 0)
                {
                    draftOrder.TotalAmount = draftOrderItemList.Sum(o => o.Amount);
                    db.DraftOrderItems.AddRange(draftOrderItemList);
                    return result = db.SaveChanges();
                }

            }
            return 0;
        }
        private void saveOrderBtn_Click(object sender, EventArgs e)
        {
            //保存头信息
            //TODO
            if (orderNoTxt.Text != GetNewOrderNo())
            {
                orderNoTxt.Text = GetNewOrderNo();
            }
            var draftOrder = db.DraftOrders.Where(o => o.OrderNo == orderNoTxt.Text).FirstOrDefault();
            if (draftOrder != null)
            {
                MessageBox.Show("存在该草稿单！"); return;
            }
            var result = SaveDraftOrder();
            if (result > 0)
            {
                MessageBox.Show("保存成功！");
            }
        }
        private int GetIntBiggerZero(int[] intlist)
        {
            int result = 0;
            foreach (var p in intlist)
            {
                if (p > 0) result++;
            }
            return result;
        }

        private void dataGridView1_CellEnter(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex >= 0 && e.ColumnIndex == 0 && dataGridView1.Focused)
            {
                var form = new ProductSelectFrm();
                var result = form.ShowDialog();
                dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = form.productNo;
            }
        }

        private void refreshBtn_Click(object sender, EventArgs e)
        {

        }

        /// <summary>
        /// 打印预览
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void printShowBtn_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(orderNoTxt.Text))
            {
                var draftOrder = db.DraftOrders.Where(o => o.OrderNo == orderNoTxt.Text).FirstOrDefault();
                var result = 0;
                result = SaveDraftOrder();
                draftOrder = db.DraftOrders.Where(o => o.OrderNo == orderNoTxt.Text).FirstOrDefault();
                //result = 1;
                if (result > 0)
                {
                    var draftOrderItems = db.DraftOrderItems.Where(o => o.DraftOrderId == draftOrder.Id).ToList();
                    if (draftOrderItems != null && draftOrderItems.Count > 0)
                    {
                        Export(draftOrder, draftOrderItems, dataGridView1);
                    }
                }
                else MessageBox.Show("需要保存草稿单才能打印预览！");
            }
        }

        private void Export(DraftOrder draftOrder, List<DraftOrderItem> draftOrderItems, DataGridView dataGridView, string xlxName = "草稿单")
        {
            try
            {
                var linelength = 19;
                var draftprint = GetDraftPrint();
                string tempFile = Path.GetTempFileName();
                //string ls_fileNeme = System.IO.Path.ChangeExtension(tempFile, ".rep");
                //File.Move(ls_file, ls_fileNeme);//修改文件扩展名
                //using (FileStream fs = new FileStream(ls_fileNeme, FileMode.Open))
                //{
                //    StreamWriter sw = new StreamWriter(fs, Encoding.Unicode);
                //    sw.WriteLine("what are you doing");
                //    sw.Flush();
                //    sw.Close();
                //}
                //FolderBrowserDialog fpath = new FolderBrowserDialog();
                //fpath.ShowDialog();
                //var path = fpath.SelectedPath;
                //if (string.IsNullOrEmpty(path))
                //{
                //    MessageBox.Show("请选择保存路径！");
                //    return;
                //}
                var dt = Helper.GetDgvToTable(dataGridView);
                //获取指定虚拟路径的物理路径
                //string path ="D:\\";
                //读取 License 文件
                //Stream stream = (Stream)File.OpenRead(path);
                //注册 License
                //Aspose.Cells.License li = new Aspose.Cells.License();
                //li.SetLicense(stream);
                //创建一个工作簿
                Aspose.Cells.Workbook workbook = new Aspose.Cells.Workbook();
                //创建一个 sheet 表
                Aspose.Cells.Worksheet worksheet = workbook.Worksheets[0];
                //设置 sheet 表名称
                worksheet.Name = dt.TableName;
                Aspose.Cells.Cell cell;
                int rowIndex = 0;   //行的起始下标为 0
                int colIndex = 0;   //列的起始下标为 0
                                    //设置标题

                cell = worksheet.Cells[rowIndex, colIndex + 0];
                cell.PutValue(draftprint.Name);
                Style style = cell.GetStyle();

                style.Font.Name = "宋体";
                style.Font.Size = 20;
                style.Font.Color = System.Drawing.Color.Black;
                style.HorizontalAlignment = TextAlignmentType.Center;
                style.VerticalAlignment = TextAlignmentType.Center;
                cell.SetStyle(style);
                worksheet.Cells.Merge(0, 0, 2, linelength);//
                rowIndex += 2;
                cell = worksheet.Cells[rowIndex, colIndex + 0];
                cell.PutValue("<草稿单>  <未付款>");
                style.Font.Name = "微软雅黑";
                style.Font.Size = 12;
                cell.SetStyle(style);
                worksheet.Cells.Merge(rowIndex, 0, 2, linelength);//
                rowIndex += 2;
                cell = worksheet.Cells[rowIndex, 0];
                cell.PutValue(draftprint.Address);
                style.Font.Name = "宋体";
                style.Font.Size = 12;
                cell.SetStyle(style);
                //cell = worksheet.Cells[rowIndex, 1];
                //cell.PutValue("电话：020-89888087  186 6602 2088");
                worksheet.Cells.Merge(rowIndex, 0, 1, linelength);//
                rowIndex++;
                cell = worksheet.Cells[rowIndex, 0];
                cell.PutValue(draftprint.TelePhone);
                worksheet.Cells.Merge(rowIndex, 0, 1, linelength);//
                //style = cell.GetStyle();
                style.Font.Name = "宋体";
                style.Font.Size = 12;
                cell.SetStyle(style);
                rowIndex++;

                cell = worksheet.Cells[rowIndex, 0];
                cell.PutValue(draftprint.Mobile);
                worksheet.Cells.Merge(rowIndex, 0, 1, linelength);//
                //style = cell.GetStyle();
                style.Font.Name = "宋体";
                style.Font.Size = 12;
                cell.SetStyle(style);
                rowIndex++;

                cell = worksheet.Cells[rowIndex, colIndex + 0];
                cell.PutValue("客户名称：" + draftOrder.CompanyName + "-" + draftOrder.Liaison + "           日期：" + draftOrder.CreateTime.ToString("yyyy年MM月dd日"));
                //cell = worksheet.Cells[rowIndex, colIndex + 1];
                //cell.PutValue("日期：" + draftOrder.CreateTime.ToString("yyyy年MM月dd日"));
                worksheet.Cells.Merge(rowIndex, 0, 1, linelength);//
                style.Font.Name = "宋体";
                style.Font.Size = 12;
                cell.SetStyle(style);
                rowIndex++;
                //176 8880 2118    186 2044 8833
                //设置列名
                for (int i = 0; i < dt.Columns.Count; i++)
                {
                    //if (dt.Columns[i].ColumnName == "备注") continue;
                    //获取第一行的每个单元格
                    cell = worksheet.Cells[rowIndex, colIndex + i];
                    //设置列名
                    cell.PutValue(dt.Columns[i].ColumnName);
                    style.Font.Name = "宋体";
                    style.Font.Size = 12;
                    cell.SetStyle(style);
                }

                //跳过第一行，第一行写入了列名
                rowIndex++;
                //写入数据
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    //var index= dt.Columns..ColumnName == "商品编号"
                    if (dt.Rows[i].ItemArray[0].ToString().Length <= 0) continue;
                    for (int j = 0; j < dt.Columns.Count; j++)
                    {
                        if (dt.Columns[j].ColumnName == "备注") continue;
                        cell = worksheet.Cells[rowIndex, colIndex + j];
                        cell.PutValue(dt.Rows[i][j]);
                        style.Font.Name = "宋体";
                        style.Font.Size = 12;
                        cell.SetStyle(style);

                    }
                    rowIndex++;
                }
                //合计
                rowIndex += 5;
                cell = worksheet.Cells[rowIndex, colIndex + 0];
                cell.PutValue("合计：");
                style.Font.Name = "宋体";
                style.Font.Size = 14;
                cell.SetStyle(style);
                //计算汇总
                //卷数
                int columnIndex = 0;
                for (int i = 0; i < dt.Columns.Count; i++)
                {
                    if (dt.Columns[i].ColumnName == "卷数") columnIndex = i;
                }
                if (columnIndex > 0)
                {
                    cell = worksheet.Cells[rowIndex, columnIndex + 0];
                    cell.PutValue(draftOrderItems.Sum(o => o.Roll_Num));
                    style.Font.Name = "宋体";
                    style.Font.Size = 14;
                    cell.SetStyle(style);
                    //draftOrderItems
                }
                //数量 
                columnIndex = 0;
                for (int i = 0; i < dt.Columns.Count; i++)
                {
                    if (dt.Columns[i].ColumnName == "数量") columnIndex = i;
                }
                if (columnIndex > 0)
                {
                    cell = worksheet.Cells[rowIndex, columnIndex + 0];
                    cell.PutValue(draftOrderItems.Sum(o => o.Quantity));
                    style.Font.Name = "宋体";
                    style.Font.Size = 14;
                    cell.SetStyle(style);
                }
                //价格  
                //columnIndex = 0;
                //for (int i = 0; i < dt.Columns.Count; i++)
                //{
                //    if (dt.Columns[i].ColumnName == "价格") columnIndex = i;
                //}
                //if (columnIndex > 0)
                //{
                //    cell = worksheet.Cells[rowIndex, columnIndex + 0];
                //    cell.PutValue(draftOrderItems.Select(o => o.Quantity).FirstOrDefault());
                //    style = cell.GetStyle();
                //    style.Font.Name = "宋体";
                //    style.Font.Size = 14;
                //    style.HorizontalAlignment = TextAlignmentType.Center;
                //    cell.SetStyle(style);
                //}
                //金额
                columnIndex = 0;
                for (int i = 0; i < dt.Columns.Count; i++)
                {
                    if (dt.Columns[i].ColumnName == "金额") columnIndex = i;
                }
                if (columnIndex > 0)
                {
                    cell = worksheet.Cells[rowIndex, columnIndex + 0];
                    cell.PutValue(draftOrderItems.Sum(o => o.Amount));
                    style.Font.Name = "宋体";
                    style.Font.Size = 14;
                    cell.SetStyle(style);
                }

                rowIndex++;
                cell = worksheet.Cells[rowIndex, colIndex + 0];
                cell.PutValue("汇款账号：");
                style.Font.Name = "宋体";
                style.Font.Size = 13;
                cell.SetStyle(style);
                cell = worksheet.Cells[rowIndex, colIndex + 1];
                cell.PutValue(draftprint.Account);
                style.Font.Name = "宋体";
                style.Font.Size = 13;
                style.HorizontalAlignment = TextAlignmentType.Left;
                style.VerticalAlignment = TextAlignmentType.Center;
                cell.SetStyle(style);
                worksheet.Cells.Merge(rowIndex, 1, 1, linelength - 1);//
                rowIndex++;
                cell = worksheet.Cells[rowIndex, colIndex + 0];
                cell.PutValue("汇款账号：");
                style.Font.Name = "宋体";
                style.Font.Size = 13;
                style.HorizontalAlignment = TextAlignmentType.Center;
                style.VerticalAlignment = TextAlignmentType.Center;
                cell.SetStyle(style);
                cell = worksheet.Cells[rowIndex, colIndex + 1];
                cell.PutValue(draftprint.BankCard1);
                style.Font.Name = "宋体";
                style.Font.Size = 13;
                style.HorizontalAlignment = TextAlignmentType.Left;
                style.VerticalAlignment = TextAlignmentType.Center;
                cell.SetStyle(style);
                worksheet.Cells.Merge(rowIndex, 1, 1, linelength - 1);//
                rowIndex++;
                cell = worksheet.Cells[rowIndex, colIndex + 0];
                cell.PutValue("汇款账号：");
                style.Font.Name = "宋体";
                style.Font.Size = 13;
                style.HorizontalAlignment = TextAlignmentType.Center;
                style.VerticalAlignment = TextAlignmentType.Center;
                cell.SetStyle(style);
                cell = worksheet.Cells[rowIndex, colIndex + 1];
                cell.PutValue(draftprint.BankCard2);
                style.Font.Name = "宋体";
                style.Font.Size = 13;
                style.HorizontalAlignment = TextAlignmentType.Left;
                style.VerticalAlignment = TextAlignmentType.Center;
                cell.SetStyle(style);
                worksheet.Cells.Merge(rowIndex, 1, 1, linelength - 1);//

                //温馨提示：尊敬的客户收到货后，如若发现面料有质量问题，请勿开裁，并于3天内联系我司解决。一经裁剪或加工，恕不退换，谢谢合作！
                rowIndex++;
                cell = worksheet.Cells[rowIndex, colIndex + 0];
                cell.PutValue("温馨提示：尊敬的客户收到货后，如若发现面料有质量问题，请勿开裁，并于3天内联系我司解决。一经裁剪或加工，恕不退换，谢谢合作！");
                worksheet.Cells.Merge(rowIndex, 0, 2, linelength);//
                style.Font.Name = "宋体";
                style.Font.Size = 9;
                style.Font.Color = System.Drawing.Color.Black;
                style.HorizontalAlignment = TextAlignmentType.Center;
                style.VerticalAlignment = TextAlignmentType.Center;
                cell.SetStyle(style);
                //自动列宽
                worksheet.AutoFitColumns();
                setColumnWithAuto(worksheet);
                var PrintArea = "A0:R" + (worksheet.Cells.MaxRow + 1).ToString();
                var rowCount = worksheet.Cells.MaxRow + 2;
                var columnCount = worksheet.Cells.MaxColumn + 1;
                for (int i = 0; i < rowCount; i++)
                {
                    for (int j = 0; j < columnCount; j++)
                    {
                        var styleCell = worksheet.Cells[i, j];
                        style = styleCell.GetStyle();
                        var bordercolor = Color.Black;
                        style.Borders[BorderType.TopBorder].LineStyle = CellBorderType.Thin;
                        style.Borders[BorderType.TopBorder].Color = bordercolor;
                        style.Borders[BorderType.BottomBorder].LineStyle = CellBorderType.Thin;
                        style.Borders[BorderType.BottomBorder].Color = bordercolor;
                        style.Borders[BorderType.LeftBorder].LineStyle = CellBorderType.Thin;
                        style.Borders[BorderType.LeftBorder].Color = bordercolor;
                        style.Borders[BorderType.RightBorder].LineStyle = CellBorderType.Thin;
                        style.Borders[BorderType.RightBorder].Color = bordercolor;
                        styleCell.SetStyle(style);
                    }
                }
                //Aspose.Cells.Range wstrange = worksheet.Cells.CreateRange(0, 0, worksheet.Cells.MaxRow + 1, worksheet.Cells.MaxColumn + 1);
                //StyleFlag stFlag = new StyleFlag();
                //stFlag.All = true;
                //wstrange.ApplyStyle(style, stFlag);
                //设置导出文件路径
                //path = HttpContext.Current.Server.MapPath("Export/");
                //设置新建文件路径及名称
                string tempFileXlsx = Path.GetTempFileName();
                string ls_fileNemeXlsx = System.IO.Path.ChangeExtension(tempFileXlsx, ".xlsx");
                string savePath = ls_fileNemeXlsx;// path + "\\" + xlxName + "-" + DateTime.Now.ToString("yyyyMMddHH-mm-ss") + ".xlsx";
                //创建文件
                FileStream file = new FileStream(savePath, FileMode.CreateNew);
                //关闭释放流，不然没办法写入数据
                file.Close();
                file.Dispose();

                //保存至指定路径
                workbook.Save(savePath);
                PageSetup pageSetup = worksheet.PageSetup;
                pageSetup.Orientation = PageOrientationType.Landscape;
                pageSetup.LeftMargin = 1;
                pageSetup.RightMargin = 1;
                pageSetup.BottomMargin = 1;
                pageSetup.TopMargin = 1;
                //pageSetup.PrintGridlines = true;
                pageSetup.PrintArea = PrintArea;// "A2:J29";
                //pageSetup.
                //Apply different Image / Print options.
                Aspose.Cells.Rendering.ImageOrPrintOptions options = new Aspose.Cells.Rendering.ImageOrPrintOptions();

                //Set the Printing page property
                options.PrintingPage = PrintingPageType.IgnoreStyle;
                //Render the worksheet
                ImageOrPrintOptions imgOptions = new ImageOrPrintOptions();
                ImageFormat imageFormat = ImageFormat.Jpeg;
                imgOptions.ImageFormat = imageFormat;
                //Set only one page would be rendered for the image
                imgOptions.OnePagePerSheet = true;
                imgOptions.PrintingPage = PrintingPageType.IgnoreBlank;

                //Create the SheetRender object based on the sheet with its
                //ImageOrPrintOptions attributes
                //SheetRender sr = new SheetRender(sheet, imgOptions);
                //send to printer
                string tempFileJpeg = Path.GetTempFileName();
                string ls_fileNemeJpeg = System.IO.Path.ChangeExtension(tempFileJpeg, ".xlsx");
                var strPrinterName = ls_fileNemeJpeg;// path + "\\" + xlxName + "-" + DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss") + ".jpeg";
                //创建一个图表选项的对象
                //ImageOrPrintOptions imgOptions = new ImageOrPrintOptions();
                //设置图片类型
                //imgOptions.ImageFormat = ImageFormat.Png;
                //获取第一张工作表
                Worksheet sheet = workbook.Worksheets[0];
                //创建一个纸张底色渲染对象
                SheetRender sr = new SheetRender(sheet, imgOptions);
                sr.ToImage(0, strPrinterName);
                PrintPictureForm printPictureForm = new PrintPictureForm(strPrinterName);
                printPictureForm.ShowDialog();

                worksheet = null;
                workbook = null;
            }
            catch (Exception ex)
            {
                MessageBox.Show("导出失败！" + ex.ToString());
            }
        }
        void setColumnWithAuto(Worksheet sheet)
        {
            Cells cells = sheet.Cells;
            int columnCount = cells.MaxColumn;  //获取表页的最大列数
            int rowCount = cells.MaxRow;        //获取表页的最大行数

            for (int col = 0; col < columnCount; col++)
            {
                sheet.AutoFitColumn(col, 0, rowCount);
            }
            for (int col = 0; col < columnCount + 1; col++)
            {
                cells.SetColumnWidthPixel(col, cells.GetColumnWidthPixel(col) + 20);
                //if (col == columnCount)
                //    cells.SetColumnWidthPixel(col, cells.GetColumnWidthPixel(col) + 150);
            }
            for (int row = 0; row < rowCount; row++)
            {
                sheet.AutoFitRow(row, 0, columnCount);
            }
            for (int row = 0; row < rowCount; row++)
            {
                cells.SetRowHeightPixel(row, cells.GetRowHeightPixel(row) + 10);
            }

        }

        private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            if (dataGridView1.CurrentRow.Cells["ColorType"].Selected == true && dataGridView1.CurrentRow.Cells["ColorType"].Value != null)
            {
                string txt = dataGridView1.CurrentRow.Cells["ColorType"].Value.ToString();
                if (!txt.EndsWith("#"))
                    dataGridView1.CurrentRow.Cells["ColorType"].Value = txt + "#";
            }
        }
        public DraftPrint GetDraftPrint()
        {
            var draftprint1 = new DraftPrint()
            {
                Floor = "1",
                Name = "輝達紡織",
                Address = "地址：广州市海珠区中大国际轻纺城首层D1071档",
                Account = "支付宝账号：13710459998 王锦福",
                //Mobile = "手机：1366248838   159 8923 6663",
                TelePhone = "电话：020-89888087   186 6602 2088   176 8880 2118    186 2044 8833",
                BankCard1 = "农行：6228 4800 8339 4852 616     户名：王淑芳",
                BankCard2 = "交行：6222 6007 1000 9066 004     户名：王淑芳"
            };
            var draftprint3 = new DraftPrint()
            {
                Floor = "3",
                Name = "輝興紡織",
                Address = "地址：广州市中大国际轻纺城三楼E3A018-019档",
                Account = "支付宝账号：13702421892 王淑芳",
                Mobile = "手机：136 6244 8838   159 8923 6663",
                TelePhone = "电话：020-89261836 89779838   传真020-89889877",
                BankCard1 = "农行：6228 4800 8305 9054 219 户名：王淑芳",
                BankCard2 = "工行：6222 0836 0200 4331 200 户名：王淑芳"
            };
            ClothContext cloth = new ClothContext();
            if (cloth.GetFloor() == "---一楼")
                return draftprint1;
            else
                return draftprint3;
        }
    }
}
